﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TS2015.Models;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Text;
using System.Data.OleDb;
using System.Data;

namespace TS2015.Areas.Admin.Controllers
{
    public class AccoutManagementController : Controller
    {
        TS2015Context db = new TS2015Context();
        // GET: Admin/AccoutManagement
        List<string> error = new List<string>();
        string count;
        bool CheckDecentralize, CheckFuntion, CheckLink;
        int MaChucNang;
        #region Acting

        public ActionResult Acting()
        {
            if (!Request.IsAjaxRequest())
                return View();

            return PartialView();
        }
        public ActionResult ReadActing([DataSourceRequest] DataSourceRequest request)
        {
            return Json(db.TbQuyens.ToDataSourceResult(request));
        }

        //[ValidateAntiForgeryToken]
        //public ActionResult CreateActing([DataSourceRequest] DataSourceRequest request, TbQuyen data)
        //{
        //    if (data != null && ModelState.IsValid)
        //    {
        //        db.TbQuyens.Add(data);
        //        db.SaveChanges();
        //    }
        //    return Json(ModelState.ToDataSourceResult());
        //}
        //public ActionResult UpdateActing([DataSourceRequest] DataSourceRequest request, TbQuyen data)
        //{
        //    if (data != null && ModelState.IsValid)
        //    {
        //        db.Entry(data).State = EntityState.Modified;
        //        db.SaveChanges();
        //    }
        //    return Json(ModelState.ToDataSourceResult());
        //}
        public ActionResult DestroyActing([DataSourceRequest] DataSourceRequest request, TbQuyen data)
        {
            try
            {
                if (data != null)
                {
                    TbQuyen itemdata = db.TbQuyens.First(item => item.MaQuyen == data.MaQuyen);
                    db.TbQuyens.Remove(itemdata);
                    db.SaveChanges();
                }
            }
            catch (Exception)
            {

                Response.Write("Bạn không thể xóa Quyền này! Dữ liệu liên quan đến Quyền này vẫn tồn tại!");
            }

            return Json(ModelState.ToDataSourceResult());
        }
        //[HttpPost]
        //[ValidateAntiForgeryToken]
        //public ActionResult ImportActing(HttpPostedFileBase FileImport)
        //{
        //    bool state = false;
        //    string mess = "";
        //    if (FileImport != null)
        //    {
        //        // thuc hien thao tac tai day
        //        if (FileImport.ContentLength > 0)
        //        {
        //            string Extension = System.IO.Path.GetExtension(FileImport.FileName);
        //            if (Extension == ".xls" || Extension == ".xlsx")
        //            {
        //                string path = string.Concat(Server.MapPath("~/Uploads/File/" + DateTime.Now.ToString("MMddyyyyHHmmssfff") + FileImport.FileName));
        //                //if (System.IO.File.Exists(path))
        //                //{

        //                //    System.IO.File.Delete(path);
        //                //}
        //                FileImport.SaveAs(path);
        //                OleDbConnection oledbcon = new OleDbConnection("provider=microsoft.ace.oledb.12.0;data source=" + path + ";extended properties=excel 12.0;");
        //                oledbcon.Open();
        //                DataTable ExcelSheets = oledbcon.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
        //                string SpreadSheetName = ExcelSheets.Rows[0]["TABLE_NAME"].ToString();
        //                OleDbCommand oledbcmd = new OleDbCommand("Select * from [" + SpreadSheetName + "]", oledbcon);
        //                OleDbDataAdapter oledbda = new OleDbDataAdapter(oledbcmd);

        //                DataTable dt = new DataTable();
        //                var ListDecentralizes = db.TbQuyens.Select(m => m.Quyen);
        //                TbQuyen item;
        //                oledbda.Fill(dt);
        //                if (dt.Rows.Count > 0)
        //                {
        //                    if (!dt.Columns.Contains("Quyền"))
        //                    {
        //                        error.Add("Cột Quyền không tồn tại!");
        //                        goto next;
        //                    }
        //                    for (int i = 0; i < dt.Rows.Count - 1; i++)
        //                    {
        //                        foreach (var a in ListDecentralizes)
        //                        {
        //                            CheckDecentralize = false;
        //                            if (a.ToString().ToLower().Trim() == dt.Rows[i]["Quyền"].ToString().ToLower().Trim())
        //                            {
        //                                CheckDecentralize = true;
        //                                break;
        //                            }
        //                        }
        //                        //try
        //                        //{
        //                        if (!CheckDecentralize)
        //                        {
        //                            item = new TbQuyen();
        //                            item.Quyen = dt.Rows[i]["Quyền"].ToString().Trim();
        //                            item.TrangThai = 1;
        //                            db.TbQuyens.Add(item);

        //                        }
        //                        else
        //                        {
        //                            error.Add("Quyền: " + dt.Rows[i]["Quyền"].ToString() + " đã tồn tại!");
        //                        }
        //                        //}
        //                        //catch
        //                        //{
        //                        //}
        //                    }
        //                    db.SaveChanges();
        //                    for (int k = 0; k < error.Count; k++)
        //                    {
        //                        count += " + " + error[k].ToString() + "<br/>";
        //                    }
        //                next:
        //                    state = true;
        //                    mess = "Thực hiện chèn thành công " + (dt.Rows.Count - error.Count) + " bản ghi!";
        //                    //TempData["Message"] = "Lưu thành công!";
        //                }
        //                else
        //                {
        //                    Response.Write("Bạn phải nhập file định dạng excel!");
        //                }
        //                oledbcon.Close();
        //                System.IO.File.Delete(path);
        //            }

        //        }
        //    }
        //    else
        //        mess = "Có lỗi.";

        //    return Json(new { State = state, Message = mess });
        //}
        #endregion
        #region Funtion
        public JsonResult GetFuntion()
        {
            return Json(db.TbChucNangs.ToList(), JsonRequestBehavior.AllowGet);
        }
        public ActionResult Funtion()
        {
            if (db.TbChucNangs.ToList().Count > 0)
            {
                ViewBag.ChucNang = db.TbChucNangs.ToList();
            }

            if (!Request.IsAjaxRequest())
                return View();

            return PartialView();
        }
        public ActionResult ReadFuntion([DataSourceRequest] DataSourceRequest request)
        {
            return Json(db.TbChucNangs.ToDataSourceResult(request));
        }

        //[ValidateAntiForgeryToken]
        public ActionResult CreateFuntion([DataSourceRequest] DataSourceRequest request, TbChucNang data)
        {
            if (data != null && ModelState.IsValid)
            {
                db.TbChucNangs.Add(data);
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        public ActionResult UpdateFuntion([DataSourceRequest] DataSourceRequest request, TbChucNang data)
        {
            if (data != null && ModelState.IsValid)
            {
                db.Entry(data).State = EntityState.Modified;
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        public ActionResult DestroyFuntion([DataSourceRequest] DataSourceRequest request, TbChucNang data)
        {
            if (data != null)
            {
                TbChucNang itemdata = db.TbChucNangs.First(item => item.MaCN == data.MaCN);
                db.TbChucNangs.Remove(itemdata);
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ImportFuntion(HttpPostedFileBase FileImport)
        {
            bool state = false;
            string mess = "";
            if (FileImport != null)
            {
                // thuc hien thao tac tai day
                if (FileImport.ContentLength > 0)
                {
                    string Extension = System.IO.Path.GetExtension(FileImport.FileName);
                    if (Extension == ".xls" || Extension == ".xlsx")
                    {
                        string path = string.Concat(Server.MapPath("~/Uploads/File/" + DateTime.Now.ToString("MMddyyyyHHmmssfff") + FileImport.FileName));
                        //if (System.IO.File.Exists(path))
                        //{

                        //    System.IO.File.Delete(path);
                        //}
                        FileImport.SaveAs(path);
                        OleDbConnection oledbcon = new OleDbConnection("provider=microsoft.ace.oledb.12.0;data source=" + path + ";extended properties=excel 12.0;");
                        oledbcon.Open();
                        DataTable ExcelSheets = oledbcon.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                        string SpreadSheetName = ExcelSheets.Rows[0]["TABLE_NAME"].ToString();
                        OleDbCommand oledbcmd = new OleDbCommand("Select * from [" + SpreadSheetName + "]", oledbcon);
                        OleDbDataAdapter oledbda = new OleDbDataAdapter(oledbcmd);

                        DataTable dt = new DataTable();
                        var ListFuntions = db.TbChucNangs;
                        TbChucNang item;
                        oledbda.Fill(dt);
                        if (dt.Rows.Count > 0)
                        {
                            if (!dt.Columns.Contains("Chức năng"))
                            {
                                error.Add("Cột Chức năng không tồn tại!");
                                goto next;
                            }
                            if (!dt.Columns.Contains("Link"))
                            {
                                error.Add("Đường Link không tồn tại!");
                                goto next;
                            }
                            if (!dt.Columns.Contains("Chức năng cha"))
                            {
                                error.Add("Cột Chức năng cha không tồn tại!");
                                goto next;
                            }
                            for (int i = 0; i < dt.Rows.Count - 1; i++)
                            {
                                if (dt.Rows[i]["Chức năng cha"].ToString().Trim() == "")
                                {
                                    MaChucNang = 0;
                                }
                                else
                                {
                                    foreach (var a in ListFuntions)
                                    {
                                        if (a.TenCN.ToLower().Trim() == dt.Rows[i]["Chức năng cha"].ToString().ToLower().Trim())
                                        {
                                            MaChucNang = a.MaCN;
                                            break;
                                        }
                                    }
                                }
                                foreach (var a in ListFuntions)
                                {
                                    CheckLink = false;
                                    if (a.Link.ToLower().Trim() == dt.Rows[i]["Link"].ToString().ToLower().Trim())
                                    {
                                        CheckLink = true;
                                        break;
                                    }
                                }
                                foreach (var a in ListFuntions)
                                {
                                    CheckFuntion = false;
                                    if (a.TenCN.ToLower().Trim() == dt.Rows[i]["Chức năng"].ToString().ToLower().Trim())
                                    {
                                        CheckFuntion = true;
                                        break;
                                    }
                                }
                                //try
                                //{
                                if (!CheckLink && !CheckFuntion)
                                {
                                    item = new TbChucNang();
                                    item.TenCN = dt.Rows[i]["Chức năng"].ToString().Trim();
                                    item.Link = dt.Rows[i]["Link"].ToString().Trim();
                                    item.MaCNCha = MaChucNang;
                                    item.TrangThai = 1;
                                    db.TbChucNangs.Add(item);
                                    db.SaveChanges();
                                }
                                else
                                {
                                    error.Add("Chức năng: " + dt.Rows[i]["Chức năng"].ToString() + " đã tồn tại!");
                                }
                                //}
                                //catch
                                //{
                                //}
                            }

                            for (int k = 0; k < error.Count; k++)
                            {
                                count += " + " + error[k].ToString() + "<br/>";
                            }
                        next:
                            state = true;
                            mess = "Thực hiện chèn thành công " + (dt.Rows.Count - error.Count - 1) + " bản ghi!";
                            //TempData["Message"] = "Lưu thành công!";
                        }
                        else
                        {
                            Response.Write("Bạn phải nhập file định dạng excel!");
                        }
                        oledbcon.Close();
                        System.IO.File.Delete(path);
                    }

                }
            }
            else
                mess = "Có lỗi.";

            return Json(new { State = state, Message = mess });
        }
        #endregion
        #region Add Acting
        public ActionResult AddActing(string id)
        {
            List<TbChucNang> all = new List<TbChucNang>();
            all = db.TbChucNangs.OrderBy(m => m.MaCNCha).ToList();
            var idrequest = db.TbChucNang_Quyen;

            if (id != null && ModelState.IsValid)
            {
                if (idrequest.Count() != 0)
                {
                    ViewBag.IDRequest = idrequest.Count();
                    ViewBag.TrangThai = new SelectList(GetTrangThai().ToString().ToList(), "Value", "Text", db.TbChucNangs.Select(m => m.TrangThai).First());
                    int idacting = int.Parse(id);
                    var x = db.TbChucNang_Quyen.Where(m => m.MaQuyen == idacting);
                    ViewBag.Funtion = x.Select(m => m.MaCN).ToArray();
                    ViewBag.Acting = (from c in x
                                      join d in db.TbQuyens on c.MaQuyen equals d.MaQuyen
                                      where c.MaQuyen == idacting
                                      select d.Quyen).FirstOrDefault();
                }
                //ViewBag.TrangThai = new SelectList(GetTrangThai().ToString().ToList(), "Value", "Text");
            }
            ViewBag.TrangThai = new SelectList(GetTrangThai().ToString().ToList(), "Value", "Text");
            if (!Request.IsAjaxRequest())
                return View(all);

            return PartialView(all);
        }
        [HttpPost]
        [ActionName("AddActing")]
        public ActionResult Post_AddActing()
        {
            TbQuyen Quyen;
            TbChucNang_Quyen ChucNang_Quyen;
            if (Request.Form["checkedFiles"] != null)
            {

                string[] Checked = Request.Form["checkedFiles"].Split(',');

                //var idrequest = db.TbChucNang_Quyen;
                if (Request.Form["MyActing"] != null)
                {
                    string nameacting = Request.Form["MyActing"].Trim();
                    int requestidacting = db.TbQuyens.Where(m => m.Quyen == nameacting).FirstOrDefault().MaQuyen;
                    //
                    //var idacting = db.TbQuyens.Where(m => m.Quyen == nameacting).FirstOrDefault().MaQuyen;
                    var listidfuntion_acting = db.TbChucNang_Quyen.Where(m => m.MaQuyen == requestidacting);
                    if (listidfuntion_acting != null)
                    {
                        foreach (var a in listidfuntion_acting)
                        {

                            db.TbChucNang_Quyen.Remove(a);
                        }
                        db.SaveChanges();
                    }
                    for (int i = 0; i < Checked.Length; i++)
                    {
                        //db.TbChucNang_Quyen.Remove(id);
                        //var idacting = db.TbQuyens.Where(m => m.Quyen == nameacting).FirstOrDefault().MaQuyen;
                        ChucNang_Quyen = new TbChucNang_Quyen { MaQuyen = requestidacting, MaCN = int.Parse(Checked[i]), TrangThai = 1 };
                        db.TbChucNang_Quyen.Add(ChucNang_Quyen);
                    }
                    db.SaveChanges();
                }
                else
                {
                    string actingname = Request.Form["txtActing"].Trim();

                    if (db.TbQuyens.Select(m => m.Quyen).FirstOrDefault() != actingname)
                    {
                        Quyen = new TbQuyen { Quyen = actingname, TrangThai = 1 };
                        db.TbQuyens.Add(Quyen);
                        db.SaveChanges();
                        for (int i = 0; i < Checked.Length; i++)
                        {

                            var idacting = db.TbQuyens.Where(m => m.Quyen == actingname).FirstOrDefault().MaQuyen;
                            ChucNang_Quyen = new TbChucNang_Quyen { MaQuyen = idacting, MaCN = int.Parse(Checked[i]), TrangThai = 1 };
                            db.TbChucNang_Quyen.Add(ChucNang_Quyen);
                            db.SaveChanges();
                        }
                    }
                }
            }
            //id.FormatWith("");
            return RedirectToAction("Acting");
        }
        #endregion
        #region List Accout
        public ActionResult GetTrangThai()
        {
            List<SelectListItem> TrangThai = new List<SelectListItem>();
            TrangThai.Add(new SelectListItem { Text = "Sử dụng", Value = "1" });
            TrangThai.Add(new SelectListItem { Text = "Không sử dụng", Value = "0" });
            ViewBag.TrangThai = TrangThai;
            return View();
        }
        public ActionResult ListAccout()
        {
            ViewBag.TrangThai = GetTrangThai();
            ViewBag.Quyen = db.TbQuyens.ToList();
            if (!Request.IsAjaxRequest())
                return View();

            return PartialView();
        }
        public ActionResult ReadListAccout([DataSourceRequest] DataSourceRequest request)
        {
            return Json(db.TbNguoiDungs.ToDataSourceResult(request));
        }
        public ActionResult DestroyListAccout([DataSourceRequest] DataSourceRequest request, TbNguoiDung data)
        {
            if (data != null)
            {
                TbNguoiDung itemdata = db.TbNguoiDungs.First(item => item.TenDangNhap == data.TenDangNhap);
                db.TbNguoiDungs.Remove(itemdata);
                db.SaveChanges();
            }
            return Json(ModelState.ToDataSourceResult());
        }
        #endregion
        #region Add Accout
        public ActionResult AddAccout(string id)
        {
            TbNguoiDung User = new TbNguoiDung();
            //if(ModelState.IsValid)
            //{
            if (id != null)
            {
                ViewBag.IDRequest = id;
                User = db.TbNguoiDungs.First(m => m.TenDangNhap == id);

                ViewBag.Quyen = new SelectList(db.TbQuyens.ToList(), "MaQuyen", "Quyen", User.MaQuyen);
                ViewBag.TrangThai = new SelectList(GetTrangThai().ToString().ToList(), "Value", "Text", User.KhoaTaiKhoan);
                
            }
            else
            {
                ViewBag.Quyen = new SelectList(db.TbQuyens.ToList(), "MaQuyen", "Quyen");
                ViewBag.TrangThai = new SelectList(GetTrangThai().ToString().ToList(), "Value", "Text");
            }
            //s}

            if (!Request.IsAjaxRequest())
                return View(User);

            return PartialView(User);
        }
        [HttpPost]
        public ActionResult AddAccout(TbNguoiDung item, string id)
        {
            bool state = false;
            string mess = "";
            if (item != null)
            {
                if (id != null)
                {
                    //foreach (var a in id)
                    //{
                    //    a
                    //}
                    item.TenDangNhap = Request.Form["UserName"].Trim();
                    item.MatKhau = DuLieuChung.MaHoaMD5(item.MatKhau);
                    item.RandomPass = "1234zxcv";
                    item.MaQuyen = item.MaQuyen;
                    db.Entry(item).State = EntityState.Modified;
                    SaveChanges(db);
                    state = true;
                    mess = "Thực hiện sửa thành công!";
                }
                else
                {

                    if (db.TbNguoiDungs.Where(m => m.TenDangNhap == item.TenDangNhap).Count() == 0)
                    {
                        item.MatKhau = DuLieuChung.MaHoaMD5(item.MatKhau);
                        item.RandomPass = "1234zxcv";
                        item.MaQuyen = item.MaQuyen;
                        db.TbNguoiDungs.Add(item);
                        SaveChanges(db);
                        state = true;
                        mess = "Thực hiện thêm thành công!";
                    }

                }

            }
            ViewBag.Quyen = db.TbQuyens.ToList();
            //mess = "Lỗi!";
            return View("ListAccout");
        }
        #endregion
        private void SaveChanges(DbContext context)
        {
            try
            {
                context.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                StringBuilder sb = new StringBuilder();

                foreach (var failure in ex.EntityValidationErrors)
                {
                    sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
                    foreach (var error in failure.ValidationErrors)
                    {
                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                        sb.AppendLine();
                    }
                }

                throw new DbEntityValidationException(
                    "Entity Validation Failed - errors follow:\n" +
                    sb.ToString(), ex
                ); // Add the original exception as the innerException
            }
        }
    }
}